package com.example.blackmarket.utils;

import android.util.Log;

import com.example.blackmarket.configration.Config;
import com.example.blackmarket.entities.JsonWebToken;
import com.example.blackmarket.module.Base.BaseApplication;
import com.google.gson.Gson;

import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 拦截器拦截请求，在请求头添加token，暂时先不判断过不过期
 */
public class TokenInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        String token = BaseApplication.get("token",null);
        Response response;
        Request originalRequest;
        if(token!=null){//如果存储了token则附带token请求
            Log.d("TokenInterceptor",token);
            originalRequest = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer " + token)
                    .build();
        }
        else{//如果没有存储token（对应第一次登录和注册的情况，直接请求）
            Log.d("Null token","None token stored");
            originalRequest =  chain.request();
        }

        response = chain.proceed(originalRequest);

        //根据和服务端的约定判断token过期
        if (isTokenExpired(response)) {
            Log.d("TokenInterceptor", "自动刷新Token,然后重新请求数据");
            //同步请求方式，获取最新的Token
            String newToken = getNewToken();
            if(newToken!=null){//如果同步登录失败或者没有存储用户密码则获取到的token为空
                //使用新的Token，创建新的请求
                Request newRequest = chain.request()
                        .newBuilder()
                        .header("Authorization", "Bearer " + newToken)
                        .build();
                //重新请求
                return chain.proceed(newRequest);
            }
            BaseApplication.showToast("用户会话过期，请重新登录");
        }

        return response;
    }

    /**
     * 根据Response，判断Token是否失效
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) {
        return response.code() == 401;
    }

    /**
     * 同步请求方式，获取最新的Token
     * @return
     */
    private synchronized String getNewToken() throws IOException {
        BaseApplication.set("token", null);//清空原来过期的token
        String newToken = null;
        String studentNumber = BaseApplication.get("studentNumber",null);
        String password = BaseApplication.get("password",null);
        if(studentNumber!=null && password!=null){
            Response response = OkHttpClientUtil.getInstance().syncLogin(Config.getUrl() + "/auth/" + studentNumber + "/" + password);
            if(response.isSuccessful()){
                assert response.body() != null;
                JsonWebToken jsonWebToken = new Gson().fromJson(response.body().string(), JsonWebToken.class);
                newToken = jsonWebToken.getToken();
            }
        }
        return newToken;
    }
}
